package com.my.xq.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.my.wechat.controller.WxTemplateMesController;
import com.my.xq.domain.entity.Court;
import com.my.xq.domain.entity.CourtRole;
import com.my.xq.domain.entity.CourtRole_Proprietor;
import com.my.xq.domain.entity.CourtYwhSettings;
import com.my.xq.domain.entity.Doorplate;
import com.my.xq.domain.entity.Plan;
import com.my.xq.domain.entity.RenWu;
import com.my.xq.repository.CourtRepository;
import com.my.xq.repository.CourtRoleBindRepository;
import com.my.xq.repository.CourtRoleRepository;
import com.my.xq.repository.CourtYwhSettingsRepository;
import com.my.xq.repository.DoorplateRepository;
import com.my.xq.repository.PlanRepository;
import com.my.xq.repository.RenWuCreateRepository;
import com.my.xq.repository.RenWuRepository;
import com.sskj.common.util.CalendarUtil;
import com.sskj.core.annotation.ControllerLogExeTime;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;

@RestController
@RequestMapping("/task")
@Component(value = "timeTaskServiceXq")
public class XqTaskService {
	@Autowired
	RenWuRepository rwRepository;

	@Autowired
	RenWuCreateRepository renWuCreateRepository;

	@Autowired
	DoorplateRepository doorplateRepository;

	@Autowired
	CourtRepository courtRepository;

	@Autowired
	CourtRoleRepository courtRoleRepository;

	@Autowired
	CourtRoleBindRepository courtRoleBindRepository;

	@Autowired
	CourtYwhSettingsRepository courtYwhSettingsRepository;

	@Autowired
	WxMpService wxService;

	@Autowired
	PlanRepository planRepository;

	@Value(value = "${wechat.mp.voteTempleteCode}")
	private String voteTempleteCode;

	@Value(value = "${sskj.conf.webDomain}")
	private String webDomain;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "业委会选举结果定时任务", log = false)
	@RequestMapping(value = "/ywh/vote/result/exec", method = { RequestMethod.GET })
	public void calculateYwhVoteResult() throws Exception {
		calculateYwhVoteResult(true);
	}

	public void execution() throws Exception {
		calculateYwhVoteResult(false);
		closeFangAnVote();
	}

	/**
	 * 计算投票结果
	 * 
	 * @param ignore
	 *            是否忽略投票任务结束时间
	 */
	private void calculateYwhVoteResult(boolean ignore) throws Exception {
		// 获取正在执行中的任务
		List<RenWu> rwList = rwRepository.taskFindRenWuActive();
		for (int i = 0; i < rwList.size(); i++) {
			RenWu rw = rwList.get(i);
			Date d = rw.getEndTime();
			Date now = new Date();
			int res = now.compareTo(d);
			if (ignore || (res == 1 && rw.isActive())) {
				boolean isOver = true;
				// 需要结束任务,同时根据层级发起下一层任务
				List<String> bulidingList = doorplateRepository.groupByBuilding(rw.getCourtId());
				if (!rw.getCode().equals("CAST04")) {
					RenWu newRenwu = new RenWu();
					newRenwu.setCourtId(rw.getCourtId());
					if (rw.getCode().equals("CAST01")) {
						// 需要根据票数选出合适的人
						for (int m = 0; m < bulidingList.size(); m++) {
							String building = bulidingList.get(m);
							List<String> unitList = doorplateRepository.groupByUnit(rw.getCourtId(), building);
							for (int j = 0; j < unitList.size(); j++) {
								String unit = unitList.get(j);
								List<Doorplate> list = doorplateRepository.findUnitVotes(rw.getCourtId(), unit,
										building);
								if (list != null && !list.isEmpty()) {
									CourtYwhSettings courtYwhSettings = courtYwhSettingsRepository.findUnit(rw.getCourtId(),
											unit, building);
									int countUnitSettings = 1;
									if (courtYwhSettings != null) {
										countUnitSettings = courtYwhSettings.getCountMember();
									}
									int tempUnit = 0;
									int countUnit = 0;
									for (Doorplate dp : list) {
										if (tempUnit < countUnitSettings) {
											addRole(dp, "单元长");
											tempUnit++;
											countUnit = dp.getCountUnit();
										} else if (tempUnit == countUnitSettings) {
											if (countUnit == dp.getCountUnit()) {
												addRole(dp, "单元长");
												tempUnit++;
											} else {
												break;
											}
										} else {
											break;
										}
									}

									// 更新本层任务Create的状态
									renWuCreateRepository.closeRenWuCreateCAST01(rw.getCourtId(), rw.getCode(), building, unit);
								} else {
									isOver = false;
								}
							}
						}
						if (isOver) {
							newRenwu.setCode("CAST02");
						}

					} else if (rw.getCode().equals("CAST02")) {
						for (int m = 0; m < bulidingList.size(); m++) {
							String building = bulidingList.get(m);
							List<Doorplate> list = doorplateRepository.findBuildingVotes(rw.getCourtId(), building);
							if (list != null && !list.isEmpty()) {
								CourtYwhSettings courtYwhSettings = courtYwhSettingsRepository.findBuilding(rw.getCourtId(),
										building);
								int countBuildingSettings = 1;
								if (courtYwhSettings != null) {
									countBuildingSettings = courtYwhSettings.getCountMember();
								}
								int tempBuilding = 0;
								int countBuilding = 0;
								for (Doorplate dp : list) {
									if (tempBuilding < countBuildingSettings) {
										addRole(dp, "楼栋长");
										tempBuilding++;
										countBuilding = dp.getCountBuilding();
									} else if (tempBuilding == countBuildingSettings) {
										if (countBuilding == dp.getCountBuilding()) {
											addRole(dp, "楼栋长");
											tempBuilding++;
										} else {
											break;
										}
									} else {
										break;
									}
								}

								// 更新本层任务Create的状态
								renWuCreateRepository.closeRenWuCreateCAST02(rw.getCourtId(), rw.getCode(), building);

							} else {
								isOver = false;
							}
						}

						if (isOver) {
							newRenwu.setCode("CAST03");
						}
					} else if (rw.getCode().equals("CAST03")) {
						List<Doorplate> list = doorplateRepository.findMemberVotes(rw.getCourtId());
						if (list != null && !list.isEmpty()) {
							Court c = courtRepository.get(rw.getCourtId());
							int countMemberSettings = 7;
							if (c != null) {
								countMemberSettings = c.getWyCount();
							}
							for (Doorplate door : list) {
								if (countMemberSettings == 0) {
									break;
								}
								addRole(door, "委员");
								countMemberSettings--;
							}

							// 更新本层任务Create的状态
							renWuCreateRepository.closeRenWuCreate(rw.getCourtId(), rw.getCode());
							newRenwu.setCode("CAST04");
						} else {
							isOver = false;
						}
					} else {
						logger.error("任务Code错误");
						isOver = false;
					}
					if (isOver) {
						Calendar ca = Calendar.getInstance();
						ca.add(Calendar.DATE, 3); // 默认期限为3天
						// 更新下层任务Create的状态
						renWuCreateRepository.openRenWuCreate(now, ca.getTime(), newRenwu.getCourtId(),
								newRenwu.getCode());

						// 更新下一层级任务的状态
						RenWu r = rwRepository.findRenWuByCourtANDCode(newRenwu.getCourtId(), newRenwu.getCode());
						r.setStartTime(now);
						r.setEndTime(ca.getTime());
						r.setActive(true);
						r.setOver(false);
						rwRepository.save(r);

						rw.setActive(false);
						rw.setOver(true);
						rw.setModifiedTime(new Date());

						rwRepository.save(rw);
					}

				} else {
					List<Doorplate> list = doorplateRepository.findMaxHeadVotes(rw.getCourtId());
					if (list != null && !list.isEmpty()) {
						addRole(list.get(0), "主任");
						rw.setActive(false);
						rw.setOver(true);
						rw.setModifiedTime(new Date());

						rwRepository.save(rw);
						// 更新本层任务Create的状态
						renWuCreateRepository.closeRenWuCreate(rw.getCourtId(), rw.getCode());
					}
				}

			}
		}
	}

	private void closeFangAnVote() {
		Date now = new Date();
		// 开始执行另外一项任务，判断时间关闭投票方案
		List<Plan> planList = planRepository.findAll();
		if (!planList.isEmpty()) {
			for (int i = 0; i < planList.size(); i++) {
				Plan plan = planList.get(i);
				int planState = plan.getPlanState();
				if (planState == 2) {
					// 判断开始时间
					Date planStartTime = plan.getPlanStartTime();
					int compareR = now.compareTo(planStartTime);
					if (compareR == 1) { // 开启投票方案
						plan.setPlanState(3);
						planRepository.save(plan);
					}
				}
				if (planState == 3) {
					// 判断结束时间
					Date planEndTime = plan.getPlanEndTime();
					int compareR = now.compareTo(planEndTime);
					if (compareR == 1) { // 开启投票方案
						plan.setPlanState(4);
						planRepository.save(plan);
					}
				}
			}
		}
	}

	private void addRole(Doorplate dp, String roleName) {

		CourtRole cr = courtRoleRepository.findCourtRoleByName(roleName);
		CourtRole_Proprietor crpr = new CourtRole_Proprietor();
		crpr.setDoorPlateId(dp.getId());
		crpr.setRoleId(cr.getId());
		crpr.setRoleName(cr.getRoleName());
		crpr.setCourtId(dp.getCourtId());
		// 先去查询数据库中是否已经存在相同的记录
		CourtRole_Proprietor cpr = courtRoleBindRepository.findCourtRoleByName(dp.getId(), cr.getId());
		if (cpr != null) {
			logger.error("数据库中存在相同门牌号和角色的记录");
		} else {
			courtRoleBindRepository.save(crpr);
			String message = "";
			String url = "http://" + webDomain + "#/home/vote/ywh/org/" + dp.getCourtId();
			if ("单元长".equals(roleName)) {
				// 被选为单元长的人有成为楼栋长的资格
				dp.setCastBuilding(true);
				message = "恭喜您成为单元长，楼栋长竞选开始！";
				url = "http://" + webDomain + "#/home/vote/ywh/c/" + dp.getCourtId();
			} else if ("楼栋长".equals(roleName)) {
				// 被选为楼栋长的人有成为委员的资格
				dp.setCastMember(true);
				message = "恭喜您成为楼栋长，委员竞选开始！";
				url = "http://" + webDomain + "#/home/vote/ywh/c/" + dp.getCourtId();
			} else if ("委员".equals(roleName)) {
				// 被选为委员的人有成为主任的资格
				dp.setCastHead(true);
				message = "恭喜您成为委员，主任竞选开始！";
				url = "http://" + webDomain + "#/home/vote/ywh/c/" + dp.getCourtId();
			} else if ("主任".equals(roleName)) {
				message = "您已成功当选主任！点击链接查看详情！";
				url = "http://" + webDomain + "#/home/vote/ywh/org/" + dp.getCourtId();
			}
			doorplateRepository.save(dp);
			// 给该用户发送开始竞选楼栋长的模板消息
			if (null != dp.getOpenId()) {
				WxTemplateMesController wmc = new WxTemplateMesController();
				try {
					Court c = courtRepository.get(dp.getCourtId());
					wxService.getTemplateMsgService().sendTemplateMsg(wmc.getTemplate(dp.getOpenId(), c.getName(),
							message, CalendarUtil.getDate(), url, voteTempleteCode));
				} catch (WxErrorException e) {
					logger.error("发送模板消息失败");
					e.printStackTrace();
				}
			}
		}
	}
}
